package com.sqpoll.android.poll;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.sqpoll.android.R;
import com.sqpoll.android.group.Group;

/**
 * The activity to select a target for new poll.
 * 
 * @author Younggue Bae
 */
public class PollTargetActivity extends SherlockFragmentActivity {

	public static final String TAG = "PollTargetActivity";

	private TargetSeparatedListAdapter mAdapter;
	private ListView mListView;
	private Button mButtonStartPoll;
	private Map<Integer, RadioButton> mRadioButtons = new HashMap<Integer, RadioButton>();
	private EditText mEditTextNewGroup;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_poll_target);

		ActionBar actionBar = getSupportActionBar();
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(true);

		List<PollTarget> itemsOpen = loadOpenTarget();
		List<PollTarget> itemsNewGroup = loadNewGroupTarget();
		List<PollTarget> itemsGroup = loadGroupTargets();
		mAdapter = new TargetSeparatedListAdapter(this);
		TargetListAdapter adapterOpen = new TargetListAdapter(this, itemsOpen);
		TargetListAdapter adapterNewGroup = new TargetListAdapter(this, itemsNewGroup);
		TargetListAdapter adapterGroup = new TargetListAdapter(this, itemsGroup);
		mAdapter.addSection(getString(R.string.text_target_select_open_poll), adapterOpen);
		mAdapter.addSection(getString(R.string.text_target_select_new_group), adapterNewGroup);
		mAdapter.addSection(getString(R.string.text_target_select_exist_group), adapterGroup);

		mListView = (ListView) findViewById(R.id.list_view_target);
		mListView.setAdapter(mAdapter);

		mButtonStartPoll = (Button) findViewById(R.id.button_start_poll);
		mButtonStartPoll.setOnClickListener(mStartPollButtonClickListener);
	}

	OnClickListener mStartPollButtonClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
		}
	};

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		}

		return true;
	}

	/**
	 * Adapter for poll target separated list.
	 * 
	 */
	public class TargetSeparatedListAdapter extends BaseAdapter {
		private Map<String, Adapter> mSections = new LinkedHashMap<String, Adapter>();
		private ArrayAdapter<String> mHeaders;
		private final static int TYPE_SECTION_HEADER = 0;

		public TargetSeparatedListAdapter(Context context) {
			mHeaders = new ArrayAdapter<String>(context, R.layout.list_header);
		}

		public void addSection(String section, Adapter adapter) {
			this.mHeaders.add(section);
			this.mSections.put(section, adapter);
		}

		@Override
		public int getCount() {
			// total together all sections, plus one for each section header
			int total = 0;
			for (Adapter adapter : this.mSections.values())
				total += adapter.getCount() + 1;
			return total;
		}

		@Override
		public Object getItem(int position) {
			for (Object section : this.mSections.keySet()) {
				Adapter adapter = mSections.get(section);
				int size = adapter.getCount() + 1;

				// check if position inside this section
				if (position == 0)
					return section;
				if (position < size)
					return adapter.getItem(position - 1);

				// otherwise jump into next section
				position -= size;
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public int getViewTypeCount() {
			// assume that headers count as one, then total all sections
			int total = 1;
			for (Adapter adapter : this.mSections.values())
				total += adapter.getViewTypeCount();
			return total;
		}

		@Override
		public int getItemViewType(int position) {
			int type = 1;
			for (Object section : this.mSections.keySet()) {
				Adapter adapter = mSections.get(section);
				int size = adapter.getCount() + 1;

				// check if position inside this section
				if (position == 0)
					return TYPE_SECTION_HEADER;
				if (position < size)
					return type + adapter.getItemViewType(position - 1);

				// otherwise jump into next section
				position -= size;
				type += adapter.getViewTypeCount();
			}
			return -1;
		}

		public boolean areAllItemsSelectable() {
			return false;
		}

		public boolean isEnabled(int position) {
			return (getItemViewType(position) != TYPE_SECTION_HEADER);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			int sectionnum = 0;
			for (Object section : this.mSections.keySet()) {
				Adapter adapter = mSections.get(section);
				int size = adapter.getCount() + 1;

				// check if position inside this section
				if (position == 0) {
					return mHeaders.getView(sectionnum, convertView, parent);
				}
				if (position < size) {
					return adapter.getView(position - 1, convertView, parent);
				}

				// otherwise jump into next section
				position -= size;
				sectionnum++;
			}
			return null;
		}
	}

	/**
	 * Adapter for poll target list.
	 * 
	 */
	public class TargetListAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private List<PollTarget> mItems;

		public TargetListAdapter(Context context, List<PollTarget> items) {
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mItems = items;
		}

		@Override
		public int getCount() {
			return mItems.size();
		}

		@Override
		public Object getItem(int position) {
			return mItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.list_item_target, null);

				holder.mRadioButton = (RadioButton) convertView.findViewById(R.id.radio_button);
				holder.mTargetName = (TextView) convertView.findViewById(R.id.target_name);
				holder.mNewGroupName = (EditText) convertView.findViewById(R.id.new_group_name);
				holder.mRadioButton.setOnClickListener(mRadioButtonClicklistener);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			PollTarget listItem = mItems.get(position);
			
			if (listItem.isOpenPoll()) {
				holder.mTargetName.setText(listItem.getName());
			} else if (listItem.isNewGroup()) {
				holder.mTargetName.setVisibility(View.INVISIBLE);
				holder.mNewGroupName.setVisibility(View.VISIBLE);
			} else {
				holder.mTargetName.setText(listItem.getGroup().getGroupName() + " (" + listItem.getGroup().getMemberCount()
						+ ")");
				holder.mTargetName.setVisibility(View.VISIBLE);
				holder.mNewGroupName.setVisibility(View.INVISIBLE);
			}
			
			// store radio button into map
			int radioGroup = 0;
			if (listItem.isOpenPoll()) {
				radioGroup = 10000;
			}
			else if (listItem.isNewGroup()) {
				radioGroup = 20000;
				mEditTextNewGroup = holder.mNewGroupName;
				mEditTextNewGroup.setEnabled(false);
			}
			else {
				radioGroup = 30000;
			}
			int id = radioGroup + position;
			mRadioButtons.put(id, holder.mRadioButton);
			
			holder.mRadioButton.setId(id);

			return convertView;
		}

		OnClickListener mRadioButtonClicklistener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				RadioButton rb = (RadioButton) v;
				Log.d(TAG, "target selected = " + rb.getId());
				
				if (rb.getId() == 20000) {
					if (mEditTextNewGroup != null) {
						mEditTextNewGroup.setEnabled(true);
						mEditTextNewGroup.setFocusable(true);
						mEditTextNewGroup.setFocusableInTouchMode(true);
						mEditTextNewGroup.requestFocus();
					}
				}
				else {
					if (mEditTextNewGroup != null) {
						mEditTextNewGroup.setEnabled(false);
						mEditTextNewGroup.setText(null);
					}
				}
				
				for (Map.Entry<Integer, RadioButton> entry : mRadioButtons.entrySet()) {
					if (entry.getKey() !=  rb.getId()) {
						RadioButton other = (RadioButton) entry.getValue();
						other.setChecked(false);
					}
				}
			}
		};

	}

	/**
	 * View holder for a list item.
	 * 
	 */
	class ViewHolder {
		RadioButton mRadioButton;
		TextView mTargetName;
		EditText mNewGroupName;
	}

	private List<PollTarget> loadOpenTarget() {
		List<PollTarget> items = new ArrayList<PollTarget>();

		PollTarget item = new PollTarget();
		item.setOpenPoll(true);
		item.setName(getString(R.string.text_target_open_poll));

		items.add(item);

		return items;
	}

	private List<PollTarget> loadNewGroupTarget() {
		List<PollTarget> items = new ArrayList<PollTarget>();

		PollTarget item = new PollTarget();
		item.setNewGroup(true);

		items.add(item);

		return items;
	}

	private List<PollTarget> loadGroupTargets() {

		List<PollTarget> items = new ArrayList<PollTarget>();

		PollTarget item = new PollTarget();
		Group group = new Group();
		group.setGroupName("Family");
		group.setMemberCount(5);
		item.setGroup(group);

		items.add(item);

		item = new PollTarget();
		group = new Group();
		group.setGroupName("School");
		group.setMemberCount(10);
		item.setGroup(group);

		items.add(item);

		item = new PollTarget();
		group = new Group();
		group.setGroupName("Work");
		group.setMemberCount(15);
		item.setGroup(group);

		items.add(item);

		item = new PollTarget();
		group = new Group();
		group.setGroupName("Internet community");
		group.setMemberCount(570);
		item.setGroup(group);

		items.add(item);

		return items;
	}

}